package com.neulogistics.contrib.procuredcenter.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.contrib.procuredcenter.api.application.converter.GoodsPOVMConverter;
import com.neulogistics.contrib.procuredcenter.api.application.converter.GoodsQueryPOConverter;
import com.neulogistics.contrib.procuredcenter.api.application.viewmodel.GoodsViewModel;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.po.GoodsPO;
import com.neulogistics.contrib.procuredcenter.infrastructure.persistence.orm.service.IGoodsPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsQueryService implements IGoodsQueryService {
    @Resource
    IGoodsPOService goodsPOService;

    @Override
    public GoodsViewModel getById(Integer goodsId) {
        GoodsPO goodsPO = goodsPOService.getById(goodsId);
        GoodsViewModel goodsViewModel = GoodsPOVMConverter.POToVM(goodsPO);
        return goodsViewModel;
    }

    @Override
    public Page<GoodsViewModel> page(GoodsQuery goodsQuery) {
        // 取出条件
        GoodsPO goodsPOQuery = GoodsQueryPOConverter.queryToPO(goodsQuery);
        long current = goodsQuery.getPageNum();
        long pageSize = goodsQuery.getPageSize();

        // 查询
        QueryWrapper<GoodsPO> queryWrapper = new QueryWrapper<>(goodsPOQuery);
        Page<GoodsPO> page = goodsPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构造结果
        Page<GoodsViewModel> viewModelPage = new Page<>(current, pageSize);
        List<GoodsViewModel> viewModelList = page.getRecords().stream()
                .map(GoodsPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }
}
